package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022/11/11 15:32
 */
@Controller
@SuppressWarnings("all")
public class IndexController {


    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 方式一：网站首页 -- 页面渲染
     * @return
     */
    @GetMapping(value = {"/", "index.html"})
    public String index(Model model) {
        // 远程调用获取数据
        Result result = productFeignClient.getBaseCategoryList();
        model.addAttribute("list", result.getData());
        return "index/index";
    }

    /**
     * 方式二：网站首页 -- 生成页面，使用nginx作为静态资源服务器进行代理
     * @return
     */
    @GetMapping("createIndex")
    @ResponseBody
    public Result createIndex() {
        // 远程调用获取数据
        Result result = productFeignClient.getBaseCategoryList();
        // 获取上下文对象
        Context context = new Context();
        // 设置模板的位置显示的数据
        context.setVariable("list",result.getData());
        FileWriter writer = null;
        try {
            writer = new FileWriter("D:\\code\\java_project\\guli_mall_project\\gmall-parent\\web\\web-all\\src\\main\\resources\\templates\\index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 生成静态页面
        templateEngine.process("index/index", context, writer);
        return Result.ok();
    }
}
